<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>青少年服饰销售分析系统 - 用户管理</title>
    <link rel="stylesheet" href="theme-dark.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#B399D4',  // 淡紫色
                        secondary: '#D8BFD8',  // 蓟色
                        tertiary: '#F0E6FF',  // 更淡的紫色
                        dark: '#663399',  // 深紫色
                        light: '#FAF5FF',  // 淡紫色背景
                        accent1: '#9370DB',  // 中紫色
                        accent2: '#BA55D3',  // 中等兰花紫
                        accent3: '#9932CC',  // 深兰花紫
                        accent4: '#8A2BE2',  // 蓝紫
                        accent5: '#9400D3',  // 深紫罗兰
                        accent6: '#6B7280',
                        accent7: '#9CA3AF',
                        accent8: '#D1D5DB',
                        accent9: '#F3F4F6'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-glass {
                background: rgba(255, 255, 255, 0.85);
                backdrop-filter: blur(4px);
                -webkit-backdrop-filter: blur(4px);
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-custom {
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            }
            .card-hover {
                transition: transform 0.3s ease, box-shadow 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px -5px rgba(79, 158, 253, 0.2);
            }
            .gradient-bg {
                background: linear-gradient(135deg, #B399D4 0%, #9370DB 100%);
            }
            .gradient-bg-secondary {
                background: linear-gradient(135deg, #D8BFD8 0%, #F0E6FF 100%);
            }
            .gradient-accent1 {
                background: linear-gradient(135deg, #9370DB 0%, #B399D4 100%);
            }
            .gradient-accent2 {
                background: linear-gradient(135deg, #BA55D3 0%, #9932CC 100%);
            }
            .gradient-accent3 {
                background: linear-gradient(135deg, #8A2BE2 0%, #9400D3 100%);
            }
            .animate-fade-in {
                animation: fadeIn 0.6s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
            .animate-slide-up {
                animation: slideUp 0.6s ease-out;
            }
            @keyframes slideUp {
                from { transform: translateY(20px); opacity: 0; }
                to { transform: translateY(0); opacity: 1; }
            }
            .pulse-animation {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.05); }
                100% { transform: scale(1); }
            }
            .number-change {
                transition: all 0.5s ease;
            }
            .chart-container {
                background: transparent;
                border-radius: 12px;
                padding: 1rem;
                transition: all 0.3s ease;
            }
            .chart-container:hover {
                box-shadow: 0 10px 25px -5px rgba(79, 158, 253, 0.1);
                transform: translateY(-2px);
            }
        }
    </style>
    
    <style>
        body {
            overflow-x: hidden;
            font-family: 'Inter', sans-serif;
                 overflow-x: hidden;
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #483f57 0%, #1A0A42 100%);
            color: #0d0d0e;        
        }
        
        #bg-canvas {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            pointer-events: none;
        }
        
        .sidebar {
            height: 100vh;
            width: 240px;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 100;
            overflow-y: auto;
            transition: width 0.3s ease;
        }
        
        .sidebar.collapsed {
            width: 64px;
        }
        
        .sidebar.collapsed .sidebar-text {
            display: none;
        }
        
        .sidebar.collapsed .sidebar-item {
            justify-content: center;
        }
        
        .main-content {
            margin-left: 240px;
            transition: margin-left 0.3s ease;
        }
        
        .main-content.expanded {
            margin-left: 64px;
        }
        
        .sidebar-item {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            color: #6B7280;
            transition: all 0.3s ease;
        }
        
        .sidebar-item.active {
            color: #B399D4;
            background-color: rgba(179, 153, 212, 0.1);
        }
        
        .sidebar-item:hover {
            color: #B399D4;
            background-color: rgba(179, 153, 212, 0.05);
        }
        
        .sidebar-icon {
            width: 24px;
            height: 24px;
            margin-right: 12px;
        }
        
        .scroll-trigger {
            opacity: 0;
            transform: translateY(20px);
            transition: opacity 0.6s ease-out, transform 0.6s ease-out;
        }
        
        .scroll-trigger.visible {
            opacity: 1;
            transform: translateY(0);
        }
        
        /* 实时数据指示器 */
        .live-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            background-color: #36B37E;
            border-radius: 50%;
            margin-right: 5px;
            animation: blink 1.5s infinite;
        }
        
        @keyframes blink {
            0% { opacity: 1; }
            50% { opacity: 0.3; }
            100% { opacity: 1; }
        }
        
        /* 表格样式优化 */
        .user-table th {
            background-color: rgba(179, 153, 212, 0.05);
            font-weight: 500;
        }
        
        .user-table tr:hover {
            background-color: rgba(179, 153, 212, 0.03);
        }
    </style>
</head>
<body class="bg-light font-inter">
    <!-- 主题切换按钮 -->
    <div class="theme-toggle fixed top-4 right-4 z-50">
        <button id="toggle-theme" class="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 p-2 rounded-full shadow-lg hover:shadow-xl transition-all duration-300">
            <i class="fa fa-moon-o"></i>
        </button>
    </div>
    
    <!-- 粒子画布 -->
    <canvas id="bg-canvas"></canvas>
    <canvas id="particles" class="canvas-particles"></canvas>
    
    <!-- 侧边栏导航 -->
    <div class="sidebar bg-glass shadow-lg" id="sidebar">
        <div class="p-4 border-b">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <div class="bg-primary text-white p-2 rounded-lg mr-3">
                        <i class="fa fa-line-chart text-xl"></i>
                    </div>
                    <h1 class="text-xl font-bold text-dark sidebar-text">销售分析系统</h1>
                </div>
                <button id="toggle-sidebar" class="text-gray-500 hover:text-primary">
                    <i class="fa fa-bars"></i>
                </button>
            </div>
        </div>
        
        <div class="py-4">
            <a href="dashboard.html" class="sidebar-item">
                <i class="fa fa-dashboard sidebar-icon"></i>
                <span class="sidebar-text">销售总览</span>
            </a>
            <a href="customer.html" class="sidebar-item">
                <i class="fa fa-users sidebar-icon"></i>
                <span class="sidebar-text">客户画像</span>
            </a>
            <a href="marketing.html" class="sidebar-item">
                <i class="fa fa-bullhorn sidebar-icon"></i>
                <span class="sidebar-text">营销效果</span>
            </a>
            <a href="season.html" class="sidebar-item">
                <i class="fa fa-calendar sidebar-icon"></i>
                <span class="sidebar-text">季节销售分析</span>
            </a>
            <a href="user.html" class="sidebar-item active">
                <i class="fa fa-user-circle sidebar-icon"></i>
                <span class="sidebar-text">用户管理</span>
            </a>
        </div>
        
        <div class="absolute bottom-0 w-full p-4 border-t">
            <div class="flex items-center">
                <img src="https://picsum.photos/id/1005/40/40" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
                <div class="ml-3">
                    <p class="text-sm font-medium text-dark sidebar-text">管理员</p>
                    <p class="text-xs text-gray-500 sidebar-text">admin@example.com</p>
                </div>
                <button id="logout-btn" class="ml-auto text-gray-500 hover:text-red-500">
                    <i class="fa fa-sign-out"></i>
                </button>
            </div>
        </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-content p-6">
        <!-- 顶部导航 -->
        <div class="flex justify-between items-center mb-6">
            <div class="flex items-center">
                <h2 class="text-2xl font-bold text-dark">用户管理</h2>
                <div class="ml-3 flex items-center">
                    <span class="live-indicator"></span>
                    <span class="text-sm text-green-500">实时数据</span>
                </div>
            </div>
            <div class="flex items-center space-x-4">
                <button id="add-user-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-custom">
                    <i class="fa fa-plus mr-2"></i>添加用户
                </button>
              
            </div>
        </div>
        
        
        <!-- 用户数据概览 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <!-- 总用户数 -->
            <div class="card p-6 animate-fade-in" style="animation-delay: 0.1s">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-gray-500 mb-1">总用户数</p>
                        <h3 class="text-3xl font-bold text-dark" id="total-users">25,847</h3>
                        <p class="text-sm text-green-500 mt-2">
                            <i class="fa fa-arrow-up"></i> 18.2% 较上月
                        </p>
                    </div>
                    <div class="bg-primary/10 p-3 rounded-lg">
                        <i class="fa fa-users text-primary text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 h-12">
                    <div id="users-trend-mini-1" style="width: 100%; height: 100%"></div>
                </div>
            </div>
            
            <!-- 活跃用户 -->
            <div class="card p-6 animate-fade-in" style="animation-delay: 0.2s">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-gray-500 mb-1">活跃用户</p>
                        <h3 class="text-3xl font-bold text-dark" id="active-users">12,459</h3>
                        <p class="text-sm text-green-500 mt-2">
                            <i class="fa fa-arrow-up"></i> 12.8% 较上月
                        </p>
                    </div>
                    <div class="bg-accent1/10 p-3 rounded-lg">
                        <i class="fa fa-user-circle text-accent1 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 h-12">
                    <div id="users-trend-mini-2" style="width: 100%; height: 100%"></div>
                </div>
            </div>
            
            <!-- 新增用户 -->
            <div class="card p-6 animate-fade-in" style="animation-delay: 0.3s">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-gray-500 mb-1">新增用户</p>
                        <h3 class="text-3xl font-bold text-dark" id="new-users">3,258</h3>
                        <p class="text-sm text-red-500 mt-2">
                            <i class="fa fa-arrow-down"></i> 3.4% 较上月
                        </p>
                    </div>
                    <div class="bg-accent2/10 p-3 rounded-lg">
                        <i class="fa fa-user-plus text-accent2 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 h-12">
                    <div id="users-trend-mini-3" style="width: 100%; height: 100%"></div>
                </div>
            </div>
            
            <!-- 用户流失 -->
            <div class="card p-6 animate-fade-in" style="animation-delay: 0.4s">
                <div class="flex justify-between items-start">
                    <div>
                        <p class="text-gray-500 mb-1">用户流失</p>
                        <h3 class="text-3xl font-bold text-dark" id="churn-users">854</h3>
                        <p class="text-sm text-green-500 mt-2">
                            <i class="fa fa-arrow-down"></i> 5.7% 较上月
                        </p>
                    </div>
                    <div class="bg-accent3/10 p-3 rounded-lg">
                        <i class="fa fa-user-times text-accent3 text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 h-12">
                    <div id="users-trend-mini-4" style="width: 100%; height: 100%"></div>
                </div>
            </div>
        </div>
        
        <!-- 用户分析图表 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <!-- 用户活跃度分布 -->
            <div class="chart-container scroll-trigger">
                <h3 class="text-lg font-semibold text-dark mb-4">用户活跃度分布</h3>
                <div id="activity-chart" style="width: 100%; height: 300px;"></div>
            </div>
            
            <!-- 用户地域分布 -->
            <div class="chart-container scroll-trigger">
                <h3 class="text-lg font-semibold text-dark mb-4">用户地域分布</h3>
                <div id="region-chart" style="width: 100%; height: 300px;"></div>
            </div>
            
            <!-- 用户年龄分布 -->
            <div class="chart-container scroll-trigger">
                <h3 class="text-lg font-semibold text-dark mb-4">用户年龄分布</h3>
                <div id="age-chart" style="width: 100%; height: 300px;"></div>
            </div>
        </div>
        
        <!-- 用户行为分析 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- 用户留存分析 -->
            <div class="chart-container scroll-trigger">
                <h3 class="text-lg font-semibold text-dark mb-4">用户留存分析</h3>
                <div id="retention-chart" style="width: 100%; height: 350px;"></div>
            </div>
            
            <!-- 用户行为路径 -->
            <div class="chart-container scroll-trigger">
                <h3 class="text-lg font-semibold text-dark mb-4">用户行为路径</h3>
                <div id="behavior-chart" style="width: 100%; height: 350px;"></div>
            </div>
        </div>
        
       <!-- 用户列表 -->
<div class="card p-6 scroll-trigger">
    <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold text-dark">用户列表</h3>
        <div class="flex items-center space-x-3">
            <!-- <button id="add-user-btn" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors flex items-center">
                <i class="fa fa-plus mr-2"></i> 添加用户
            </button> -->
            <!-- <div class="flex items-center">
                <span class="text-sm text-gray-500 mr-2">显示条数：</span>
                <select id="items-per-page" class="bg-white border border-gray-200 rounded-lg px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                    <option value="10">10条</option>
                    <option value="20" selected>20条</option>
                    <option value="50">50条</option>
                </select>
            </div> -->
        </div>
    </div>
    
    <!-- 搜索和过滤 -->
    <div class="flex flex-wrap gap-3 mb-4">
        <div class="relative flex-grow max-w-md">
            <input type="text" id="search-input" class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="搜索用户...">
            <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
        </div>
        <select id="role-filter" class="bg-white border border-gray-200 rounded-lg px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
            <option value="">所有角色</option>
            <option value="admin">管理员</option>
            <option value="user">普通用户</option>
        </select>
        <select id="status-filter" class="bg-white border border-gray-200 rounded-lg px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
            <option value="">所有状态</option>
            <option value="active">活跃</option>
            <option value="inactive">非活跃</option>
        </select>
    </div>
    
    <div class="overflow-x-auto">
        <table class="min-w-full user-table">
            <thead>
                <tr class="bg-gray-50">
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户ID</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户信息</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册时间</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">活跃度</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">消费金额</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户等级</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200" id="users-table-body">
                <!-- 用户数据将通过JavaScript动态填充 -->
            </tbody>
        </table>
    </div>
    
    <div class="flex justify-between items-center mt-6">
        <div class="text-sm text-gray-500">
            <span id="pagination-info">显示 1-20 条，共 <span id="total-users">0</span> 条</span>
        </div>
        <div class="flex space-x-1" id="pagination">
            <!-- 分页按钮将通过JavaScript动态填充 -->
        </div>
    </div>
</div>

<!-- 添加/编辑用户模态框 -->
<div id="user-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto transform transition-all scale-95 opacity-0" id="modal-content">
        <div class="p-6 border-b">
            <div class="flex justify-between items-center">
                <h3 class="text-xl font-semibold text-dark" id="modal-title">添加用户</h3>
                <button id="close-modal" class="text-gray-400 hover:text-gray-600">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
        </div>
        <form id="user-form" class="p-6">
            <input type="hidden" id="user-id">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="modal-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <div class="relative">
                        <input type="text" id="modal-username" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="请输入用户名" required>
                        <div id="username-error" class="text-red-500 text-xs mt-1 hidden">用户名已存在</div>
                    </div>
                </div>
                <div>
                    <label for="modal-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                    <div class="relative">
                        <input type="email" id="modal-email" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="请输入邮箱" required>
                        <div id="email-error" class="text-red-500 text-xs mt-1 hidden">邮箱格式不正确或已存在</div>
                    </div>
                </div>
                <div>
                    <label for="modal-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <div class="relative">
                        <input type="password" id="modal-password" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="请输入密码" required>
                        <button type="button" id="toggle-password" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                        <div id="password-error" class="text-red-500 text-xs mt-1 hidden">密码长度至少为6个字符</div>
                    </div>
                </div>
                <div>
                    <label for="modal-role" class="block text-sm font-medium text-gray-700 mb-1">角色</label>
                    <select id="modal-role" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <option value="user">普通用户</option>
                        <option value="admin">管理员</option>
                    </select>
                </div>
                <div>
                    <label for="modal-status" class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                    <select id="modal-status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50">
                        <option value="active">活跃</option>
                        <option value="inactive">非活跃</option>
                    </select>
                </div>
                <div>
                    <label for="modal-created-at" class="block text-sm font-medium text-gray-700 mb-1">注册时间</label>
                    <input type="text" id="modal-created-at" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 bg-gray-50" placeholder="自动生成" disabled>
                </div>
            </div>
            
            <div class="flex justify-end gap-3 mt-8">
                <button type="button" id="cancel-btn" class="px-5 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors flex items-center">
                    <i class="fa fa-times mr-2"></i> 取消
                </button>
                <button type="submit" id="save-user-btn" class="px-5 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors flex items-center">
                    <i class="fa fa-check mr-2"></i> 保存
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="delete-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl shadow-xl w-full max-w-md transform transition-all scale-95 opacity-0" id="delete-modal-content">
        <div class="p-6">
            <div class="text-center mb-4">
                <div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-red-100 mb-4">
                    <i class="fa fa-exclamation-triangle text-red-500 text-xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-900">确认删除</h3>
                <p class="text-gray-500 mt-2">确定要删除用户 <span id="delete-username" class="font-medium"></span> 吗？</p>
                <p class="text-sm text-red-500 mt-1">此操作不可撤销！</p>
            </div>
            <div class="flex justify-center gap-3 mt-6">
                <button type="button" id="cancel-delete-btn" class="px-5 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors flex items-center">
                    <i class="fa fa-times mr-2"></i> 取消
                </button>
                <button type="button" id="confirm-delete-btn" class="px-5 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center">
                    <i class="fa fa-trash mr-2"></i> 删除
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 成功提示 -->
<div id="success-toast" class="fixed bottom-4 right-4 bg-green-500 text-white px-4 py-3 rounded-lg shadow-lg transform translate-y-16 opacity-0 transition-all duration-300 flex items-center">
    <i class="fa fa-check-circle mr-2"></i>
    <span id="toast-message">操作成功</span>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
    // 用户管理
    let users = JSON.parse(localStorage.getItem('users') || '[]');
    let currentPage = 1;
    let itemsPerPage = 20;
    let searchTerm = '';
    let roleFilter = '';
    let statusFilter = '';

    // 获取用户列表
    function getUsers() {
        let filteredUsers = [...users];

        // 搜索过滤
        if (searchTerm) {
            filteredUsers = filteredUsers.filter(user => 
                user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
                user.email.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }

        // 角色过滤
        if (roleFilter) {
            filteredUsers = filteredUsers.filter(user => user.role === roleFilter);
        }

        // 状态过滤
        if (statusFilter) {
            filteredUsers = filteredUsers.filter(user => user.status === statusFilter);
        }

        return filteredUsers;
    }

    // 渲染用户表格
    function renderUsersTable() {
        const filteredUsers = getUsers();
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const paginatedUsers = filteredUsers.slice(startIndex, endIndex);

        const tableBody = document.getElementById('users-table-body');
        tableBody.innerHTML = '';

        if (paginatedUsers.length === 0) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-10 text-gray-500">
                        <i class="fa fa-search text-3xl mb-2"></i>
                        <p>未找到用户</p>
                    </td>
                </tr>
            `;
            document.getElementById('pagination-info').textContent = `显示 0 条，共 ${filteredUsers.length} 条`;
            return;
        }

        paginatedUsers.forEach(user => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors';
            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">${user.id}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 h-10 w-10">
                            <img class="h-10 w-10 rounded-full" src="https://picsum.photos/200/200?random=${user.id}" alt="用户头像">
                        </div>
                        <div class="ml-4">
                            <div class="text-sm font-medium text-gray-900">${user.username}</div>
                            <div class="text-sm text-gray-500">${user.email}</div>
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">${new Date(user.createdAt).toLocaleString()}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${user.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}">
                        ${user.status === 'active' ? '活跃' : '非活跃'}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">¥${(Math.random() * 10000).toFixed(2)}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${user.role === 'admin' ? '管理员' : '普通用户'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button class="edit-btn text-indigo-600 hover:text-indigo-900 mr-4 transition-colors flex items-center" data-id="${user.id}">
                        <i class="fa fa-pencil mr-1"></i> 编辑
                    </button>
                    <button class="delete-btn text-red-600 hover:text-red-900 transition-colors flex items-center" data-id="${user.id}" data-username="${user.username}">
                        <i class="fa fa-trash mr-1"></i> 删除
                    </button>
                </td>
            `;
            tableBody.appendChild(row);
        });

        // 更新分页信息
        document.getElementById('total-users').textContent = filteredUsers.length;
        document.getElementById('pagination-info').textContent = `显示 ${startIndex + 1}-${Math.min(endIndex, filteredUsers.length)} 条，共 ${filteredUsers.length} 条`;

        // 添加编辑和删除事件监听
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const userId = this.getAttribute('data-id');
                openEditModal(userId);
            });
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const userId = this.getAttribute('data-id');
                const username = this.getAttribute('data-username');
                openDeleteModal(userId, username);
            });
        });

        // 渲染分页
        renderPagination(filteredUsers.length);
    }

    // 渲染分页
    function renderPagination(totalItems) {
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        if (totalPages <= 1) return;

        // 首页按钮
        const firstPage = document.createElement('button');
        firstPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        firstPage.innerHTML = '<i class="fa fa-angle-double-left"></i>';
        firstPage.onclick = currentPage === 1 ? null : () => {
            currentPage = 1;
            renderUsersTable();
        };
        pagination.appendChild(firstPage);

        // 前一页按钮
        const prevPage = document.createElement('button');
        prevPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        prevPage.innerHTML = '<i class="fa fa-angle-left"></i>';
        prevPage.onclick = currentPage === 1 ? null : () => {
            currentPage = currentPage - 1;
            renderUsersTable();
        };
        pagination.appendChild(prevPage);

        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = startPage + maxVisiblePages - 1;

        if (endPage > totalPages) {
            endPage = totalPages;
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        for (let i = startPage; i <= endPage; i++) {
            const page = document.createElement('button');
            page.className = `px-3 py-1 border border-gray-200 rounded ${i === currentPage ? 'bg-primary text-white' : 'hover:bg-gray-50'}`;
            page.textContent = i;
            page.onclick = () => {
                currentPage = i;
                renderUsersTable();
            };
            pagination.appendChild(page);
        }

        // 下一页按钮
        const nextPage = document.createElement('button');
        nextPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        nextPage.innerHTML = '<i class="fa fa-angle-right"></i>';
        nextPage.onclick = currentPage === totalPages ? null : () => {
            currentPage = currentPage + 1;
            renderUsersTable();
        };
        pagination.appendChild(nextPage);

        // 末页按钮
        const lastPage = document.createElement('button');
        lastPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        lastPage.innerHTML = '<i class="fa fa-angle-double-right"></i>';
        lastPage.onclick = currentPage === totalPages ? null : () => {
            currentPage = totalPages;
            renderUsersTable();
        };
        pagination.appendChild(lastPage);
    }

    // 监听搜索输入框事件
    const searchInput = document.getElementById('search-user-input');
    searchInput.addEventListener('input', function() {
        searchTerm = this.value;
        currentPage = 1; // 重置页码为第一页
        renderUsersTable();
    });

    // 初始化渲染用户表格
    renderUsersTable();
});
document.addEventListener('DOMContentLoaded', function() {
    // 用户管理
    let users = JSON.parse(localStorage.getItem('users') || '[]');
    let currentPage = 1;
    let itemsPerPage = 20;
    let searchTerm = '';
    let roleFilter = '';
    let statusFilter = '';
    
    // 获取用户列表
    function getUsers() {
        let filteredUsers = [...users];
        
        // 搜索过滤
        if (searchTerm) {
            filteredUsers = filteredUsers.filter(user => 
                user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
                user.email.toLowerCase().includes(searchTerm.toLowerCase())
            );
        }
        
        // 角色过滤
        if (roleFilter) {
            filteredUsers = filteredUsers.filter(user => user.role === roleFilter);
        }
        
        // 状态过滤
        if (statusFilter) {
            filteredUsers = filteredUsers.filter(user => user.status === statusFilter);
        }
        
        return filteredUsers;
    }
    
    // 渲染用户表格
    function renderUsersTable() {
        const filteredUsers = getUsers();
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const paginatedUsers = filteredUsers.slice(startIndex, endIndex);
        
        const tableBody = document.getElementById('users-table-body');
        tableBody.innerHTML = '';
        
        if (paginatedUsers.length === 0) {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-10 text-gray-500">
                        <i class="fa fa-search text-3xl mb-2"></i>
                        <p>未找到用户</p>
                    </td>
                </tr>
            `;
            document.getElementById('pagination-info').textContent = `显示 0 条，共 ${filteredUsers.length} 条`;
            return;
        }
        
        paginatedUsers.forEach(user => {
            const row = document.createElement('tr');
            row.className = 'hover:bg-gray-50 transition-colors';
            row.innerHTML = `
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">${user.id}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 h-10 w-10">
                            <img class="h-10 w-10 rounded-full" src="https://picsum.photos/200/200?random=${user.id}" alt="用户头像">
                        </div>
                        <div class="ml-4">
                            <div class="text-sm font-medium text-gray-900">${user.username}</div>
                            <div class="text-sm text-gray-500">${user.email}</div>
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">${new Date(user.createdAt).toLocaleString()}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${user.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}">
                        ${user.status === 'active' ? '活跃' : '非活跃'}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">¥${(Math.random() * 10000).toFixed(2)}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${user.role === 'admin' ? '管理员' : '普通用户'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button class="edit-btn text-indigo-600 hover:text-indigo-900 mr-4 transition-colors flex items-center" data-id="${user.id}">
                        <i class="fa fa-pencil mr-1"></i> 编辑
                    </button>
                    <button class="delete-btn text-red-600 hover:text-red-900 transition-colors flex items-center" data-id="${user.id}" data-username="${user.username}">
                        <i class="fa fa-trash mr-1"></i> 删除
                    </button>
                </td>
            `;
            tableBody.appendChild(row);
        });
        
        // 更新分页信息
        document.getElementById('total-users').textContent = filteredUsers.length;
        document.getElementById('pagination-info').textContent = `显示 ${startIndex + 1}-${Math.min(endIndex, filteredUsers.length)} 条，共 ${filteredUsers.length} 条`;
        
        // 添加编辑和删除事件监听
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const userId = this.getAttribute('data-id');
                openEditModal(userId);
            });
        });
        
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const userId = this.getAttribute('data-id');
                const username = this.getAttribute('data-username');
                openDeleteModal(userId, username);
            });
        });
        
        // 渲染分页
        renderPagination(filteredUsers.length);
    }
    
    // 渲染分页
    function renderPagination(totalItems) {
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';
        
        if (totalPages <= 1) return;
        
        // 首页按钮
        const firstPage = document.createElement('button');
        firstPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        firstPage.innerHTML = '<i class="fa fa-angle-double-left"></i>';
        firstPage.onclick = currentPage === 1 ? null : () => {
            currentPage = 1;
            renderUsersTable();
        };
        pagination.appendChild(firstPage);
        
        // 前一页按钮
        const prevPage = document.createElement('button');
        prevPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        prevPage.innerHTML = '<i class="fa fa-angle-left"></i>';
        prevPage.onclick = currentPage === 1 ? null : () => {
            currentPage = currentPage - 1;
            renderUsersTable();
        };
        pagination.appendChild(prevPage);
        
        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = startPage + maxVisiblePages - 1;
        
        if (endPage > totalPages) {
            endPage = totalPages;
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const page = document.createElement('button');
            page.className = `px-3 py-1 border border-gray-200 rounded ${i === currentPage ? 'bg-primary text-white' : 'hover:bg-gray-50'}`;
            page.textContent = i;
            page.onclick = () => {
                currentPage = i;
                renderUsersTable();
            };
            pagination.appendChild(page);
        }
        
        // 下一页按钮
        const nextPage = document.createElement('button');
        nextPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        nextPage.innerHTML = '<i class="fa fa-angle-right"></i>';
        nextPage.onclick = currentPage === totalPages ? null : () => {
            currentPage = currentPage + 1;
            renderUsersTable();
        };
        pagination.appendChild(nextPage);
        
        // 末页按钮
        const lastPage = document.createElement('button');
        lastPage.className = `px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        lastPage.innerHTML = '<i class="fa fa-angle-double-right"></i>';
        lastPage.onclick = currentPage === totalPages ? null : () => {
            currentPage = totalPages;
            renderUsersTable();
        };
        pagination.appendChild(lastPage);
    }
    
    // 打开编辑模态框
    function openEditModal(userId) {
        const user = users.find(u => u.id === userId);
        if (!user) return;
        
        document.getElementById('modal-title').textContent = '编辑用户';
        document.getElementById('user-id').value = user.id;
        document.getElementById('modal-username').value = user.username;
        document.getElementById('modal-email').value = user.email;
        document.getElementById('modal-role').value = user.role;
        document.getElementById('modal-status').value = user.status;
        document.getElementById('modal-created-at').value = new Date(user.createdAt).toLocaleString();
        
        // 编辑时不要求输入密码
        document.getElementById('modal-password').removeAttribute('required');
        document.getElementById('modal-password').value = '';
        
        // 隐藏错误提示
        document.getElementById('username-error').classList.add('hidden');
        document.getElementById('email-error').classList.add('hidden');
        document.getElementById('password-error').classList.add('hidden');
        
        // 显示模态框并添加动画
        document.getElementById('user-modal').classList.remove('hidden');
        setTimeout(() => {
            document.getElementById('modal-content').classList.remove('scale-95', 'opacity-0');
            document.getElementById('modal-content').classList.add('scale-100', 'opacity-100');
        }, 10);
    }
    
    // 打开删除确认模态框
    function openDeleteModal(userId, username) {
        document.getElementById('delete-username').textContent = username;
        
        // 显示模态框并添加动画
        document.getElementById('delete-modal').classList.remove('hidden');
        setTimeout(() => {
            document.getElementById('delete-modal-content').classList.remove('scale-95', 'opacity-0');
            document.getElementById('delete-modal-content').classList.add('scale-100', 'opacity-100');
        }, 10);
        
        // 保存当前要删除的用户ID
        document.getElementById('confirm-delete-btn').setAttribute('data-id', userId);
    }
    
    // 关闭模态框
    function closeModals() {
        // 添加关闭动画
        document.getElementById('modal-content').classList.remove('scale-100', 'opacity-100');
        document.getElementById('modal-content').classList.add('scale-95', 'opacity-0');
        document.getElementById('delete-modal-content').classList.remove('scale-100', 'opacity-100');
        document.getElementById('delete-modal-content').classList.add('scale-95', 'opacity-0');
        
        // 延迟隐藏模态框，等待动画完成
        setTimeout(() => {
            document.getElementById('user-modal').classList.add('hidden');
            document.getElementById('delete-modal').classList.add('hidden');
        }, 200);
    }
    
    // 显示成功提示
    function showSuccessToast(message) {
        const toast = document.getElementById('success-toast');
        document.getElementById('toast-message').textContent = message;
        
        toast.classList.remove('translate-y-16', 'opacity-0');
        toast.classList.add('translate-y-0', 'opacity-100');
        
        setTimeout(() => {
            toast.classList.remove('translate-y-0', 'opacity-100');
            toast.classList.add('translate-y-16', 'opacity-0');
        }, 3000);
    }
    
    // 添加用户按钮点击事件
    document.getElementById('add-user-btn').addEventListener('click', function() {
        document.getElementById('modal-title').textContent = '添加用户';
        document.getElementById('user-form').reset();
        document.getElementById('user-id').value = '';
        document.getElementById('modal-created-at').value = '';
        
        // 添加时要求输入密码
        document.getElementById('modal-password').setAttribute('required', 'required');
        
        // 隐藏错误提示
        document.getElementById('username-error').classList.add('hidden');
        document.getElementById('email-error').classList.add('hidden');
        document.getElementById('password-error').classList.add('hidden');
        
        // 显示模态框并添加动画
        document.getElementById('user-modal').classList.remove('hidden');
        setTimeout(() => {
            document.getElementById('modal-content').classList.remove('scale-95', 'opacity-0');
            document.getElementById('modal-content').classList.add('scale-100', 'opacity-100');
        }, 10);
    });
    
    // 关闭模态框按钮
    document.getElementById('close-modal').addEventListener('click', closeModals);
    document.getElementById('cancel-btn').addEventListener('click', closeModals);
    document.getElementById('cancel-delete-btn').addEventListener('click', closeModals);
    
    // 点击模态框外部关闭
    document.getElementById('user-modal').addEventListener('click', function(e) {
        if (e.target === this) closeModals();
    });
    
    document.getElementById('delete-modal').addEventListener('click', function(e) {
        if (e.target === this) closeModals();
    });
    
    // 密码显示/隐藏切换
    document.getElementById('toggle-password').addEventListener('click', function() {
        const passwordInput = document.getElementById('modal-password');
        const icon = this.querySelector('i');
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    });
    
    // 表单验证
    document.getElementById('modal-username').addEventListener('input', function() {
        document.getElementById('username-error').classList.add('hidden');
    });
    
    document.getElementById('modal-email').addEventListener('input', function() {
        document.getElementById('email-error').classList.add('hidden');
    });
    
    document.getElementById('modal-password').addEventListener('input', function() {
        document.getElementById('password-error').classList.add('hidden');
    });
    
    // 保存用户表单提交事件
    document.getElementById('user-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const userId = document.getElementById('user-id').value;
        const username = document.getElementById('modal-username').value;
        const email = document.getElementById('modal-email').value;
        const password = document.getElementById('modal-password').value;
        const role = document.getElementById('modal-role').value;
        const status = document.getElementById('modal-status').value;
        
        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            document.getElementById('email-error').classList.remove('hidden');
            return;
        }
        
        // 检查用户名是否已存在
        const existingUser = users.find(u => u.username === username && u.id !== userId);
        if (existingUser) {
            document.getElementById('username-error').classList.remove('hidden');
            return;
        }
        
        // 检查邮箱是否已存在
        const existingEmail = users.find(u => u.email === email && u.id !== userId);
        if (existingEmail) {
            document.getElementById('email-error').classList.remove('hidden');
            return;
        }
        
        // 验证密码强度
        if ((!userId && !password) || (password && password.length < 6)) {
            document.getElementById('password-error').classList.remove('hidden');
            return;
        }
        
        // 禁用保存按钮，防止重复提交
        const saveBtn = document.getElementById('save-user-btn');
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';
        
        // 创建或更新用户
        let message = '';
        if (userId) {
            // 更新现有用户
            const userIndex = users.findIndex(u => u.id === userId);
            if (userIndex !== -1) {
                users[userIndex] = {
                    ...users[userIndex],
                    username,
                    email,
                    role,
                    status,
                    // 只有当密码字段有值时才更新密码
                    ...(password && { password: password })
                };
                message = '用户信息更新成功';
            }
        } else {
            // 添加新用户
            const newUser = {
                id: Date.now().toString(), // 使用时间戳作为唯一ID
                username,
                email,
                password,
                role,
                status,
                createdAt: new Date().toISOString()
            };
            users.push(newUser);
            message = '用户添加成功';
        }
        
        // 保存用户数据到localStorage
        localStorage.setItem('users', JSON.stringify(users));
        
        // 关闭模态框并刷新表格
        closeModals();
        renderUsersTable();
        
        // 显示成功消息
        showSuccessToast(message);
        
        // 恢复保存按钮状态
        setTimeout(() => {
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="fa fa-check mr-2"></i> 保存';
        }, 1000);
    });
    
    // 确认删除按钮点击事件
    document.getElementById('confirm-delete-btn').addEventListener('click', function() {
        const userId = this.getAttribute('data-id');
        
        // 不能删除自己
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser && currentUser.id === userId) {
            alert('不能删除当前登录的用户');
            closeModals();
            return;
        }
        
        // 禁用删除按钮，防止重复提交
        const deleteBtn = this;
        deleteBtn.disabled = true;
        deleteBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 删除中...';
        
        // 删除用户
        const userToDelete = users.find(u => u.id === userId);
        users = users.filter(user => user.id !== userId);
        
        // 保存用户数据到localStorage
        localStorage.setItem('users', JSON.stringify(users));
        
        // 关闭模态框并刷新表格
        closeModals();
        renderUsersTable();
        
        // 显示成功消息
        showSuccessToast(`用户 ${userToDelete.username} 删除成功`);
        
        // 恢复删除按钮状态
        setTimeout(() => {
            deleteBtn.disabled = false;
            deleteBtn.innerHTML = '<i class="fa fa-trash mr-2"></i> 删除';
        }, 1000);
    });
    
    // 搜索功能
    document.getElementById('search-input').addEventListener('input', function() {
        searchTerm = this.value.trim();
        currentPage = 1; // 重置到第一页
        renderUsersTable();
    });
    
    // 角色过滤
    document.getElementById('role-filter').addEventListener('change', function() {
        roleFilter = this.value;
        currentPage = 1; // 重置到第一页
        renderUsersTable();
    });
    
    // 状态过滤
    document.getElementById('status-filter').addEventListener('change', function() {
        statusFilter = this.value;
        currentPage = 1; // 重置到第一页
        renderUsersTable();
    });
    
    // 每页显示条数
    document.getElementById('items-per-page').addEventListener('change', function() {
        itemsPerPage = parseInt(this.value);
        currentPage = 1; // 重置到第一页
        renderUsersTable();
    });
    
    // 初始化数据
    if (users.length === 0) {
        // 添加默认管理员账户
        const defaultAdmin = {
            id: 'admin1',
            username: 'admin',
            email: 'admin@example.com',
            password: 'admin123',
            role: 'admin',
            status: 'active',
            createdAt: new Date().toISOString()
        };
        users.push(defaultAdmin);
        localStorage.setItem('users', JSON.stringify(users));
    }
    
    // 渲染用户表格
    renderUsersTable();
});
</script>

    <div class="overflow-x-auto">
        <table class="min-w-full user-table">
            <thead>
                <tr class="bg-gray-50">
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户ID</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户信息</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">注册时间</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">活跃度</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">消费金额</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户等级</th>
                    <!-- <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th> -->
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200" id="users-table">
                <!-- 用户数据由JS动态生成 -->
            </tbody>
        </table>
    </div>

    <div class="flex justify-between items-center mt-6">
        <div class="text-sm text-gray-500" id="paginationInfo">
            显示 1-20 条，共 25,847 条
        </div>
        <div class="flex space-x-1">
            <button class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 disabled:opacity-50" disabled>
                <i class="fa fa-angle-left"></i>
            </button>
            <button class="px-3 py-1 border border-gray-200 rounded bg-primary text-white">1</button>
            <button class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50">2</button>
            <button class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50">3</button>
            <button class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50">4</button>
            <button class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50">5</button>
            <button class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50">
                <i class="fa fa-angle-right"></i>
            </button>
        </div>
    </div>
</div>

<script>
// 1. 弹窗控制
const addUserBtn = document.getElementById('addUserBtn');
const addUserModal = document.getElementById('addUserModal');
const cancelAdd = document.getElementById('cancelAdd');

addUserBtn.addEventListener('click', () => {
    addUserModal.classList.remove('hidden');
});

cancelAdd.addEventListener('click', () => {
    addUserModal.classList.add('hidden');
});

// 2. 模拟添加用户逻辑（实际需对接后端接口，这里演示前端渲染）
const addUserForm = document.getElementById('addUserForm');
const usersTable = document.getElementById('users-table');

addUserForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData(addUserForm);
    const user = Object.fromEntries(formData.entries());
    
    // 模拟生成用户ID、注册时间等（实际由后端返回）
    user.userId = Date.now().toString(); 
    user.registerTime = new Date().toLocaleString();
    user.activity = '活跃';
    user.consumeAmount = '¥0.00';
    user.level = '普通用户';

    // 渲染到表格
    const row = document.createElement('tr');
    row.innerHTML = `
        <td class="px-6 py-3">${user.userId}</td>
        <td class="px-6 py-3">
            <div>${user.username}</div>
            <div>${user.email}</div>
            <div>电话：${user.phone || '未填写'}</div>
            <div>地址：${user.address || '未填写'}</div>
        </td>
        <td class="px-6 py-3">${user.registerTime}</td>
        <td class="px-6 py-3">${user.activity}</td>
        <td class="px-6 py-3">${user.consumeAmount}</td>
        <td class="px-6 py-3">${user.level}</td>
        <td class="px-6 py-3">
            <button class="text-primary mr-2">编辑</button>
            <button class="text-red-500">删除</button>
        </td>
    `;
    usersTable.appendChild(row);

    // 关闭弹窗、重置表单
    addUserModal.classList.add('hidden');
    addUserForm.reset();
    
    // 可在此处调用真实后端接口：
    // fetch('/api/addUser', { method: 'POST', body: JSON.stringify(user) }) 
    //   .then(res => res.json())
    //   .then(data => { /* 成功后处理，比如更新列表 */ });
});
</script>
    <script>
        // 主题切换功能
        document.addEventListener('DOMContentLoaded', function() {
            const toggleBtn = document.getElementById('toggle-theme');
            
            // 检查本地存储的主题偏好
            if (localStorage.getItem('theme') === 'dark' || 
                (!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
                document.body.classList.add('dark-mode');
                toggleBtn.innerHTML = '<i class="fa fa-sun-o"></i>';
            }

            // 主题切换按钮事件
            toggleBtn.addEventListener('click', function() {
                document.body.classList.toggle('dark-mode');
                const icon = document.body.classList.contains('dark-mode') ? 'sun-o' : 'moon-o';
                this.innerHTML = `<i class="fa fa-${icon}"></i>`;
                localStorage.setItem('theme', document.body.classList.contains('dark-mode') ? 'dark' : 'light');
            });
        });

        // 动态背景粒子效果
        function createParticles() {
            const canvas = document.getElementById('bg-canvas');
            const ctx = canvas.getContext('2d');
            
            // 设置canvas尺寸
            function resizeCanvas() {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;
            }
            
            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);
            
            // 创建粒子
            class Particle {
                constructor() {
                    this.x = Math.random() * canvas.width;
                    this.y = Math.random() * canvas.height;
                    this.size = Math.random() * 3 + 1;
                    this.speedX = Math.random() * 2 - 1;
                    this.speedY = Math.random() * 2 - 1;
                    this.color = `rgba(179, 153, 212, ${Math.random() * 0.7 + 0.3})`;
                }
                
                update() {
                    this.x += this.speedX;
                    this.y += this.speedY;
                    
                    if (this.size > 0.2) this.size -= 0.001;
                    
                    // 边界检测
                    if (this.x < 0 || this.x > canvas.width) this.speedX *= -1;
                    if (this.y < 0 || this.y > canvas.height) this.speedY *= -1;
                }
                
                draw() {
                    ctx.fillStyle = this.color;
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                    ctx.fill();
                }
            }
            
            // 创建粒子数组
            let particles = [];
            const particleCount = 100;
            
            function init() {
                particles = [];
                for (let i = 0; i < particleCount; i++) {
                    particles.push(new Particle());
                }
            }
            
            // 动画循环
            function animate() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 绘制连接线
                for (let a = 0; a < particles.length; a++) {
                    for (let b = a; b < particles.length; b++) {
                        const dx = particles[a].x - particles[b].x;
                        const dy = particles[a].y - particles[b].y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        
                        if (distance < 100) {
                            ctx.beginPath();
                            ctx.strokeStyle = `rgba(179, 153, 212, ${0.2 - distance/1000})`;
                            ctx.lineWidth = 0.5;
                            ctx.moveTo(particles[a].x, particles[a].y);
                            ctx.lineTo(particles[b].x, particles[b].y);
                            ctx.stroke();
                        }
                    }
                }
                
                // 更新并绘制粒子
                for (let i = 0; i < particles.length; i++) {
                    particles[i].update();
                    particles[i].draw();
                }
                
                requestAnimationFrame(animate);
            }
            
            init();
            animate();
        }
        
        // 侧边栏切换
        function setupSidebar() {
            const sidebar = document.getElementById('sidebar');
            const mainContent = document.querySelector('.main-content');
            const toggleBtn = document.getElementById('toggle-sidebar');
            
            toggleBtn.addEventListener('click', () => {
                sidebar.classList.toggle('collapsed');
                mainContent.classList.toggle('expanded');
            });
        }
        
        // 滚动动画
        function setupScrollAnimation() {
            const scrollElements = document.querySelectorAll('.scroll-trigger');
            
            const elementInView = (el, dividend = 1) => {
                const elementTop = el.getBoundingClientRect().top;
                return (
                    elementTop <= (window.innerHeight || document.documentElement.clientHeight) / dividend
                );
            };
            
            const displayScrollElement = (element) => {
                element.classList.add('visible');
            };
            
            const hideScrollElement = (element) => {
                element.classList.remove('visible');
            };
            
            const handleScrollAnimation = () => {
                scrollElements.forEach((el) => {
                    if (elementInView(el, 1.25)) {
                        displayScrollElement(el);
                    } else {
                        hideScrollElement(el);
                    }
                });
            };
            
            window.addEventListener('scroll', () => {
                handleScrollAnimation();
            });
            
            // 初始检查
            handleScrollAnimation();
        }
        
        // 生成随机数
        function getRandomNumber(min, max, decimal = 0) {
            const factor = Math.pow(10, decimal);
            return Math.round((Math.random() * (max - min) + min) * factor) / factor;
        }
        
        // 格式化货币
        function formatCurrency(num) {
            return '¥' + num.toLocaleString('zh-CN');
        }
        
        // 生成随机用户数据
        function generateRandomUserData() {
            // 基本数据
            const totalUsers = 25847;
            const activeUsers = 12459;
            const newUsers = 3258;
            const churnUsers = 854;
            
            // 用户活跃度分布
            const activityData = [
                {name: '高活跃', value: 45},
                {name: '中活跃', value: 30},
                {name: '低活跃', value: 15},
                {name: '沉睡用户', value: 10}
            ];
            
            // 用户地域分布
            const regionData = [
                {name: '北京', value: 15},
                {name: '上海', value: 12},
                {name: '广州', value: 10},
                {name: '深圳', value: 8},
                {name: '杭州', value: 7},
                {name: '成都', value: 6},
                {name: '武汉', value: 5},
                {name: '其他', value: 37}
            ];
            
            // 用户年龄分布
            const ageData = [
                {name: '12-15岁', value: 18},
                {name: '16-18岁', value: 32},
                {name: '19-22岁', value: 25},
                {name: '23-25岁', value: 15},
                {name: '26-30岁', value: 10}
            ];
            
            // 用户留存分析
            const retentionData = [];
            for (let i = 1; i <= 6; i++) {
                const data = [];
                for (let j = 1; j <= 12; j++) {
                    const baseValue = 1000 / Math.pow(1.5, i-1);
                    data.push(Math.round(baseValue + baseValue * (j/12) * 0.3 + getRandomNumber(-baseValue*0.1, baseValue*0.1)));
                }
                retentionData.push(data);
            }
            
            // 用户行为路径
            const behaviorData = [
                {source: '首页', target: '商品列表', value: 60},
                {source: '首页', target: '搜索页', value: 30},
                {source: '首页', target: '活动页', value: 10},
                {source: '商品列表', target: '商品详情', value: 70},
                {source: '商品列表', target: '分类筛选', value: 20},
                {source: '商品列表', target: '搜索页', value: 10},
                {source: '商品详情', target: '加入购物车', value: 40},
                {source: '商品详情', target: '立即购买', value: 30},
                {source: '商品详情', target: '收藏', value: 20},
                {source: '商品详情', target: '返回列表', value: 10},
                {source: '购物车', target: '结算', value: 80},
                {source: '购物车', target: '继续购物', value: 20},
                {source: '结算', target: '支付', value: 90},
                {source: '结算', target: '修改地址', value: 10},
                {source: '支付', target: '支付成功', value: 85},
                {source: '支付', target: '支付失败', value: 15}
            ];
            
            // 用户列表数据
            const userStatus = [
                {text: '活跃', class: 'bg-green-100 text-green-800'},
                {text: '休眠', class: 'bg-yellow-100 text-yellow-800'},
                {text: '流失', class: 'bg-red-100 text-red-800'}
            ];
            
            const userLevels = [
                {text: '普通会员', class: 'bg-gray-100 text-gray-800'},
                {text: '银卡会员', class: 'bg-gray-200 text-gray-800'},
                {text: '金卡会员', class: 'bg-yellow-100 text-yellow-800'},
                {text: '钻石会员', class: 'bg-blue-100 text-blue-800'}
            ];
            
            const usersData = [];
            for (let i = 0; i < 20; i++) {
                const randomStatus = userStatus[Math.floor(Math.random() * userStatus.length)];
                const randomLevel = userLevels[Math.floor(Math.random() * userLevels.length)];
                const randomAge = Math.floor(Math.random() * 19) + 12;
                const randomConsumption = Math.floor(Math.random() * 5000) + 100;
                
                usersData.push({
                    id: `USR-${20230000 + i + Math.floor(Math.random() * 1000)}`,
                    name: ['张小明', '李华', '王芳', '赵伟', '陈静', '刘芳', '张伟', '王强', '李强', '刘洋', 
                          '陈明', '黄丽', '周杰', '吴敏', '徐峰', '孙佳', '马丽', '朱琳', '胡军', '林娜'][i],
                    avatar: `https://picsum.photos/id/${1000 + i}/40/40`,
                    gender: ['男', '女'][Math.floor(Math.random() * 2)],
                    age: randomAge,
                    registerDate: `${2022 + Math.floor(Math.random() * 2)}-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
                    status: randomStatus,
                    consumption: randomConsumption,
                    level: randomLevel
                });
            }
            
            return {
                totalUsers,
                activeUsers,
                newUsers,
                churnUsers,
                activityData,
                regionData,
                ageData,
                retentionData,
                behaviorData,
                usersData
            };
        }
        
        // 更新数据卡片
        function updateDataCards(data) {
            // 总用户数
            document.getElementById('total-users').textContent = data.totalUsers.toLocaleString('zh-CN');
            
            // 活跃用户
            document.getElementById('active-users').textContent = data.activeUsers.toLocaleString('zh-CN');
            
            // 新增用户
            document.getElementById('new-users').textContent = data.newUsers.toLocaleString('zh-CN');
            
            // 用户流失
            document.getElementById('churn-users').textContent = data.churnUsers.toLocaleString('zh-CN');
            
            // 更新用户表格
            updateUsersTable(data.usersData);
        }
        
        // 更新用户表格
        function updateUsersTable(data) {
            const tableBody = document.getElementById('users-table');
            tableBody.innerHTML = '';
            
            data.forEach(user => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors';
                
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="font-medium text-gray-900">${user.id}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <img src="${user.avatar}" alt="${user.name}" class="w-8 h-8 rounded-full mr-3">
                            <div>
                                <div class="font-medium text-gray-900">${user.name}</div>
                                <div class="text-sm text-gray-500">${user.gender}，${user.age}岁</div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${user.registerDate}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${user.status.class}">${user.status.text}</span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${formatCurrency(user.consumption)}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${user.level.class}">${user.level.text}</span>
                    </td>
                    
            </tr>
        `;
        
        tableBody.appendChild(row);
    });
}

// 初始化ECharts图表
function initCharts() {
    // 迷你趋势图1 - 总用户数
    const usersTrendMini1 = echarts.init(document.getElementById('users-trend-mini-1'));
    usersTrendMini1.setOption({
        xAxis: {
            show: false
        },
        yAxis: {
            show: false
        },
        series: [{
            data: [21000, 22500, 23200, 23800, 24300, 24800, 25200, 25500, 25700, 25847],
            type: 'line',
            smooth: true,
            showSymbol: false,
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        {offset: 0, color: 'rgba(79, 158, 253, 0.5)'},
                        {offset: 1, color: 'rgba(79, 158, 253, 0.05)'}
                    ]
                }
            },
            lineStyle: {
                color: '#4F9EFD',
                width: 2
            }
        }]
    });
    
    // 迷你趋势图2 - 活跃用户
    const usersTrendMini2 = echarts.init(document.getElementById('users-trend-mini-2'));
    usersTrendMini2.setOption({
        xAxis: {
            show: false
        },
        yAxis: {
            show: false
        },
        series: [{
            data: [10500, 11000, 11200, 11500, 11800, 12000, 12200, 12300, 12400, 12459],
            type: 'line',
            smooth: true,
            showSymbol: false,
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        {offset: 0, color: 'rgba(123, 97, 255, 0.5)'},
                        {offset: 1, color: 'rgba(123, 97, 255, 0.05)'}
                    ]
                }
            },
            lineStyle: {
                color: '#7B61FF',
                width: 2
            }
        }]
    });
    
    // 迷你趋势图3 - 新增用户
    const usersTrendMini3 = echarts.init(document.getElementById('users-trend-mini-3'));
    usersTrendMini3.setOption({
        xAxis: {
            show: false
        },
        yAxis: {
            show: false
        },
        series: [{
            data: [3500, 3450, 3400, 3350, 3300, 3280, 3270, 3260, 3265, 3258],
            type: 'line',
            smooth: true,
            showSymbol: false,
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        {offset: 0, color: 'rgba(255, 125, 0, 0.5)'},
                        {offset: 1, color: 'rgba(255, 125, 0, 0.05)'}
                    ]
                }
            },
            lineStyle: {
                color: '#FF7D00',
                width: 2
            }
        }]
    });
    
    // 迷你趋势图4 - 用户流失
    const usersTrendMini4 = echarts.init(document.getElementById('users-trend-mini-4'));
    usersTrendMini4.setOption({
        xAxis: {
            show: false
        },
        yAxis: {
            show: false
        },
        series: [{
            data: [950, 920, 900, 880, 870, 860, 865, 860, 858, 854],
            type: 'line',
            smooth: true,
            showSymbol: false,
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        {offset: 0, color: 'rgba(255, 86, 48, 0.5)'},
                        {offset: 1, color: 'rgba(255, 86, 48, 0.05)'}
                    ]
                }
            },
            lineStyle: {
                color: '#FF5630',
                width: 2
            }
        }]
    });
    
    // 初始随机数据
    const initialData = generateRandomUserData();
    
    // 用户活跃度分布
    const activityChart = echarts.init(document.getElementById('activity-chart'));
    activityChart.setOption({
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
            {
                name: '用户活跃度',
                type: 'pie',
                radius: ['30%', '75%'],
                center: ['50%', '50%'],
                data: initialData.activityData.map(item => ({value: item.value, name: item.name})),
                itemStyle: {
                    borderRadius: 5,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                color: [
                    '#4F9EFD', '#7B61FF', '#FF7D00', '#FF5630'
                ]
            }
        ]
    });
    
    // 用户地域分布
    const regionChart = echarts.init(document.getElementById('region-chart'));
    regionChart.setOption({
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
            {
                name: '用户地域分布',
                type: 'pie',
                radius: ['30%', '75%'],
                center: ['50%', '50%'],
                data: initialData.regionData.map(item => ({value: item.value, name: item.name})),
                itemStyle: {
                    borderRadius: 5,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                color: [
                    '#4F9EFD', '#7B61FF', '#FF7D00', '#FF5630', '#36B37E', '#00B8D9', '#96C2FF', '#E8F3FF'
                ]
            }
        ]
    });
    
    // 用户年龄分布
    const ageChart = echarts.init(document.getElementById('age-chart'));
    ageChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: initialData.ageData.map(item => item.name),
            axisLine: {
                lineStyle: {
                    color: '#E2E8F0'
                }
            },
            axisTick: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            name: '用户比例(%)',
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    color: '#E2E8F0'
                }
            }
        },
        series: [
            {
                name: '用户比例',
                type: 'bar',
                data: initialData.ageData.map(item => item.value),
                color: '#4F9EFD',
                barWidth: '40%',
                label: {
                    show: true,
                    position: 'top',
                    color: '#4A5568'
                }
            }
        ]
    });
    
    // 用户留存分析
    const retentionChart = echarts.init(document.getElementById('retention-chart'));
    retentionChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        legend: {
            data: ['首月留存', '次月留存', '第三月留存', '第四月留存', '第五月留存', '第六月留存'],
            top: '5%',
            left: 'center'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            axisLine: {
                lineStyle: {
                    color: '#E2E8F0'
                }
            },
            axisTick: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            name: '用户数量',
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    color: '#E2E8F0'
                }
            }
        },
        series: [
            {
                name: '首月留存',
                type: 'line',
                data: initialData.retentionData[0],
                color: '#4F9EFD',
                label: {
                    show: false,
                    position: 'top',
                    color: '#4A5568'
                }
            },
            {
                name: '次月留存',
                type: 'line',
                data: initialData.retentionData[1],
                color: '#7B61FF',
                label: {
                    show: false,
                    position: 'top',
                    color: '#4A5568'
                }
            },
            {
                name: '第三月留存',
                type: 'line',
                data: initialData.retentionData[2],
                color: '#FF7D00',
                label: {
                    show: false,
                    position: 'top',
                    color: '#4A5568'
                }
            },
            {
                name: '第四月留存',
                type: 'line',
                data: initialData.retentionData[3],
                color: '#FF5630',
                label: {
                    show: false,
                    position: 'top',
                    color: '#4A5568'
                }
            },
            {
                name: '第五月留存',
                type: 'line',
                data: initialData.retentionData[4],
                color: '#36B37E',
                label: {
                    show: false,
                    position: 'top',
                    color: '#4A5568'
                }
            },
            {
                name: '第六月留存',
                type: 'line',
                data: initialData.retentionData[5],
                color: '#00B8D9',
                label: {
                    show: false,
                    position: 'top',
                    color: '#4A5568'
                }
            }
        ]
    });
    
    // 用户行为路径
    const behaviorChart = echarts.init(document.getElementById('behavior-chart'));
    
    // 处理行为路径数据
    const behaviorNodes = [];
    const behaviorLinks = [];
    
    // 添加所有节点
    initialData.behaviorData.forEach(item => {
        if (!behaviorNodes.some(node => node.name === item.source)) {
            behaviorNodes.push({name: item.source});
        }
        if (!behaviorNodes.some(node => node.name === item.target)) {
            behaviorNodes.push({name: item.target});
        }
        behaviorLinks.push({
            source: item.source,
            target: item.target,
            value: item.value
        });
    });
    
    behaviorChart.setOption({
        tooltip: {
            trigger: 'item',
            formatter: function(params) {
                if (params.value) {
                    return params.source + ' → ' + params.target + '<br/>转化率: ' + params.value + '%';
                }
                return params.name;
            }
        },
        series: [
            {
                type: 'graph',
                layout: 'force',
                data: behaviorNodes,
                links: behaviorLinks,
                roam: true,
                focusNodeAdjacency: true,
                force: {
                    repulsion: 1000,
                    edgeLength: 100
                },
                itemStyle: {
                    color: '#4F9EFD',
                    borderColor: '#fff',
                    borderWidth: 2
                },
                lineStyle: {
                    color: 'source',
                    curveness: 0.3,
                    opacity: 0.7
                },
                label: {
                    show: true,
                    position: 'right'
                }
            }
        ]
    });
    
    // 设置定时更新数据
    let refreshInterval = 5000; // 默认5秒
    let refreshTimer = null;
    
    function startRefreshTimer() {
        if (refreshTimer) clearInterval(refreshTimer);
        if (refreshInterval > 0) {
            refreshTimer = setInterval(() => {
                const newData = generateRandomUserData();
                updateDataCards(newData);
                updateCharts(newData);
            }, refreshInterval);
        }
    }
    
    // 开始定时刷新
    startRefreshTimer();
    
    // 更新图表数据
    window.updateCharts = function(newData) {
        // 用户活跃度分布
        activityChart.setOption({
            series: [
                {
                    data: newData.activityData.map(item => ({value: item.value, name: item.name}))
                }
            ]
        });
        
        // 用户地域分布
        regionChart.setOption({
            series: [
                {
                    data: newData.regionData.map(item => ({value: item.value, name: item.name}))
                }
            ]
        });
        
        // 用户年龄分布
        ageChart.setOption({
            series: [
                {
                    data: newData.ageData.map(item => item.value)
                }
            ]
        });
        
        // 用户留存分析
        retentionChart.setOption({
            series: [
                {
                    data: newData.retentionData[0]
                },
                {
                    data: newData.retentionData[1]
                },
                {
                    data: newData.retentionData[2]
                },
                {
                    data: newData.retentionData[3]
                },
                {
                    data: newData.retentionData[4]
                },
                {
                    data: newData.retentionData[5]
                }
            ]
        });
        
        // 用户行为路径
        const newBehaviorNodes = [];
        const newBehaviorLinks = [];
        
        newData.behaviorData.forEach(item => {
            if (!newBehaviorNodes.some(node => node.name === item.source)) {
                newBehaviorNodes.push({name: item.source});
            }
            if (!newBehaviorNodes.some(node => node.name === item.target)) {
                newBehaviorNodes.push({name: item.target});
            }
            newBehaviorLinks.push({
                source: item.source,
                target: item.target,
                value: item.value
            });
        });
        
        behaviorChart.setOption({
            series: [
                {
                    data: newBehaviorNodes,
                    links: newBehaviorLinks
                }
            ]
        });
    };
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    createParticles();
    setupSidebar();
    setupScrollAnimation();
    initCharts();
    
    // 初始数据
    const initialData = generateRandomUserData();
    updateDataCards(initialData);
    
    // 登出按钮
    document.getElementById('logout-btn').addEventListener('click', () => {
        if (confirm('确定要退出登录吗？')) {
            // 这里可以添加登出逻辑
            alert('已成功退出登录！');
        }
    });
    
    // 添加用户按钮
    document.getElementById('add-user-btn').addEventListener('click', () => {
        alert('请添加用户！');
    });
});
    </script>
</body>
</html>